﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Networking;

namespace Nirvana
{
    public sealed class AssetBundleInfo
    {
        private bool isHaveToken;
        private WaitLoadFileInfo waitLoadFileInfo;
        private Dictionary<string, int> assetbundleMap = new Dictionary<string, int>();

        public bool IsHaveToken()
        {
            return this.isHaveToken;
        }

        public bool isNull()
        {
            return this.waitLoadFileInfo != null;
        }

        public int GetToken(string name)
        {
            int result;
            if(assetbundleMap.TryGetValue(name,out result))
            {
                return result;
            }
            return 0;
        }

        public WaitLoadFileInfo Load(string path)
        {
            if (this.waitLoadFileInfo != null) return this.waitLoadFileInfo;
            if (this.isHaveToken) return new WaitLoadFileInfo(this);
            Debug.Log(string.Format("Start Load File Info: {0}", path));
            UnityWebRequest webrequest = UnityWebRequest.Get(path);
            AsyncOperation asyncOperation = webrequest.SendWebRequest();
            this.waitLoadFileInfo = new WaitLoadFileInfo(this, webrequest, asyncOperation);
            return this.waitLoadFileInfo;
        }

        public void Clear()
        {
            this.waitLoadFileInfo = null;
        }

        public bool ParseToken(string path)
        {
            this.assetbundleMap.Clear();
            string[] array = path.Split(new char[] { '\n', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if(array.Length %2 != 0)
            {
                Debug.LogErrorFormat("[AssetBundleInfo] Parse Length Fail1: {0}", path);
                return false;
            }

            for(int i = 0; i < array.Length; i += 2)
            {
                string abname = array[i];
                int token;
                if(!int.TryParse(array[i+1],out token))
                {
                    Debug.LogErrorFormat("[AssetBundleInfo] Parse Token Fail: {0}", array[i + 1]);
                    return false;
                }
                this.assetbundleMap.Add(abname, token);
            }
            this.isHaveToken = true;
            return true;
        }

    }
}

